import java.util.Arrays;
import java.util.Comparator;

/**
 * 稀疏矩阵类
 * 
 * @author 杨满球（本地）
 *
 */
class SparseMatrix {
	private TripleNode tripleNodes[];
	private int rows;
	private int cols;
	private int nums;

	public SparseMatrix(int maxSize) {
		tripleNodes = new TripleNode[maxSize];
		for (int i = 0; i < tripleNodes.length; i++) {
			tripleNodes[i] = new TripleNode();
		}
	}

	// 构造方法，直接对矩阵进行赋值
	public SparseMatrix(int mat[][]) {
		rows = mat.length;
		cols = mat[0].length;
		// 计算矩阵中非零元素的个数
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (mat[i][j] != 0) {
					nums++;
				}
			}
		}
		// 开辟空间
		tripleNodes = new TripleNode[nums];
		int i = 0, j = 0, k = 0;
		// 寻找非零元素并且赋值
		do {
			if (j >= cols) {
				j = 0;
				i++;
			}
			if (mat[i][j] != 0) {
				tripleNodes[k] = new TripleNode(i, j, mat[i][j]);
				k++;
			}
			j++;
		} while (k < nums);
	}

	// 对矩阵进行转制
	public SparseMatrix transpose() {
		SparseMatrix tm = new SparseMatrix(nums);
		tm.setRows(cols);
		tm.setColumns(rows);
		tm.setNums(nums);
		// 交互矩阵的行列
		for (int i = 0; i < nums; i++) {
			int row = tripleNodes[i].getColumn();
			int col = tripleNodes[i].getRow();
			int value = tripleNodes[i].getValue();
			TripleNode t = new TripleNode(row, col, value);
			tm.setValue(i, t);
		}
		// 对三元组表进行排序
		Arrays.sort(tm.getTripleNodes(), new Comparator<TripleNode>() {
			// 重写排序方法，t1在前返回-1，t1在后返回1
			@Override
			public int compare(TripleNode t1, TripleNode t2) {
				if (t1.getRow() <= t2.getRow()) {
					if (t1.getRow() == t2.getRow()) {
						if (t1.getColumn() < t2.getColumn()) {
							return -1;
						} else {
							return 1;
						}
					} else {
						return -1;
					}
				} else {
					return 1;
				}
			}
		});
		return tm;
	}

	public TripleNode[] getTripleNodes() {
		return tripleNodes;
	}

	public int getValue(int index) {
		return tripleNodes[index].getValue();
	}

	public void setValue(int index, TripleNode t) {
		tripleNodes[index] = t;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getColumns() {
		return cols;
	}

	public void setColumns(int cols) {
		this.cols = cols;
	}

	public int getNums() {
		return nums;
	}

	public void setNums(int nums) {
		this.nums = nums;
	}

	@Override
	public String toString() {
		String sString = "rows " + rows + ", cols " + cols + ", nums " + nums;
		sString += "\n-----------------------------------------------------\n";
		sString += "row\tcolumn\tvalue\n";
		for (TripleNode tripleNode : tripleNodes) {
			sString += tripleNode.toString() + "\n";
		}
		return sString;
	}
}
